<template>
  <div class="wrapper">
    <div id="cfmap">
      <div class="map-btn-left" v-if="!isReadOnly && hasKeySearch">
        <l-select-address @getSearch="getSearch"></l-select-address>
        <!-- <el-button type="primary"
          @click="getGeoByCAD('b6f5e93d1aa6e5e50c443d6708a3a9561701765697371')">上传CAD文件</el-button> -->
      </div>
      <div class="map-btn-right" v-if="!isReadOnly">
        <el-button size="small" @click="resetMap()" icon="el-icon-refresh"> </el-button>
        <l-upload-preview v-if="hasCAD" class="upload-files" v-model="folderId" :limit="1" @success="uploadSuccess"
          showFileList="popover" btnText="上传CAD文件" accept=".dwg,.dxf">
        </l-upload-preview>
        <el-button-group v-if="isLoading">
          <el-button v-if="hasDrawType.includes('point')" size="small" @click="startDraw('draw_point')" type="primary">点
          </el-button>
          <el-button v-if="hasDrawType.includes('line')" size="small" @click="startDraw('draw_line_string')"
            type="primary">线
          </el-button>
          <el-button v-if="hasDrawType.includes('polygon')" size="small" @click="startDraw('draw_polygon')"
            type="primary">面
          </el-button>
          <el-button v-if="isDraw" size="small" @click="clearAllDraw()">清除全部</el-button>
          <el-button v-if="isDraw" size="small" @click="clearSelected()">清除选中</el-button>
          <el-button v-if="isDraw" size="small" @click="saveDraw()">保存</el-button>
        </el-button-group>
      </div>
    </div>
  </div>
</template>
<script >
import cfmap from "cfmap";
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'
import * as turf from '@turf/turf'
import drawStyle from "./style.json";
// import Basemap from "./basemap.json";
export default {
  name: 'l-draw-map',
  props: {
    geoData: Object,
    isReadOnly: {
      type: Boolean,
      default: false
    },
    hasCAD: {
      type: Boolean,
      default: true,
    },
    hasKeySearch: {
      type: Boolean,
      default: true,
    },
    hasDrawType: {
      type: String,
      default: 'point,line,polygon'
    }
  },
  data() {
    return {
      mapboxmap: null,
      isDraw: true,
      drawType: '', // 绘制类型
      drawDom: null, // 绘制对象
      isLoading: false,
      keywords: "", // 地址搜索关键词

      folderId: "",

    };
  },
  mounted() {
    this.init()
  },

  methods: {
    init() {
      this.loadMap();
    },

    //加载地图
    loadMap() {
      cfmap.setConfig({
        EPSG: 3857,
      });
      this.mapboxmap = new cfmap.Map({
        container: "cfmap",
        center: [121.127710, 31.480273],
        zoom: 12,
        minZoom: 12,
        style: `${process.env.VUE_APP_BASE_GEO}v1/cf/rest/services/MapService/VM/3a0e10d8-d5a7-0f56-a47b-8e608af35b73?token=${this.geoToken}`, // 影像地图 太仓高新区
        // style: Basemap, // 影像地图 太仓高新区
      });
      this.drawDom = new MapboxDraw({
        displayControlsDefault: false,
        controls: {
          polygon: true,
          point: true,
          line_string: true,
          trash: true
        },
        styles: drawStyle,
      });
      setTimeout(() => {
        this.mapboxmap.resize()
      }, 1500);
      this.mapboxmap.on('load', () => {
        // 添加绘制工具
        this.mapboxmap.addControl(this.drawDom, 'top-right');

        if (this.geoData?.type) {
          this.loadData(this.geoData)
        }

        this.isLoading = true

      });


    },
    /** 重置视图 */
    resetMap() {
      this.mapboxmap.flyTo({
        center: [121.127710, 31.480273],
        zoom: 10.848,
        pitch: 0,
        bearing: 0,
      })
    },

    // 加载已有数据
    loadData(geo) {
      if (geo.type == 'FeatureCollection') {
        geo.features.forEach(f => {
          this.drawDom.add(f.geometry)
        })
        geo = geo.features[0]
      } else {
        this.drawDom.add(geo)
      }
      if (geo) {
        var bbox = turf.bbox(geo);
        this.mapboxmap.fitBounds(bbox, {
          minZoom: 12,
          maxZoom: 14.5,
          padding: 100,
        });
      }
    },

    // 开始绘制
    startDraw(type) {
      if (type == this.drawType) {
        this.drawType = ''
        this.isDraw = true
        this.drawDom.changeMode('simple_select')
        this.drawDom.modes.simple_select
      } else {
        this.drawType = type
        this.isDraw = true
        this.drawDom.changeMode(type)
      }
    },

    // 结束绘制
    saveDraw() {
      //   this.isDraw = false
      // 获取全部绘制空间信息
      let geo = this.drawDom.getAll()

      this.$confirm(this.$t('是否保存?'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(async () => {
        // 向表单传入绘制之后的坐标信息
        this.$emit('getDrawData', geo.features)
        // this.isDraw = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('已取消!')
        })
      })

    },
    // 清除全部绘制数据
    clearAllDraw() {
      this.drawDom.deleteAll()
    },
    // 清除当前要素
    clearSelected() {
      // 获取当前选中要素id
      let ids = this.drawDom.getSelectedIds()
      this.drawDom.delete(ids)
    },

    getSearch(data) {
      this.drawDom.deleteAll()
      if (data) {
        var { parseFromWK } = require('@/core/util/wkt.js')
        const geoData = parseFromWK(data)
        this.loadData(geoData)
      }
    },

    //#region 上传cad文件
    /** 上传文件成功 */
    uploadSuccess(e) {
      this.getGeoByCAD(e.file.id)

    },
    /** 获取geo数据 */
    async getGeoByCAD(fileId) {
      const api = window.$crud("fileconversion/dwgtofeaturecollection");
      const data = await this.$awaitWraper(api.get(fileId))

      const geoJson = {
        type: 'FeatureCollection',
        features: []
      }
      /** 上图 */
      var { parseFromWK } = require('@/core/util/wkt.js')
      data.forEach(f => {
        if(f.geometry){
          const feature = parseFromWK(f.geometry)
          if (['Polygon', 'LineString', 'Point'].includes(feature.type)) {
            geoJson.features.push({ 'type': 'Feature', 'geometry': feature })
          }
        }
      })

      this.loadData(geoJson)
      // this.isDraw = true
    },

    //#endregion



  }
};
</script>
<style lang="scss" scoped>
.wrapper {
  height: 100%;
  width: 100%;
  overflow: hidden;
  position: relative;
}
#cfmap {
  height: 100%;
  width: 100%;
}
.map-btn-right {
  position: absolute;
  z-index: 99;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 10px;
}
.map-btn-left {
  position: absolute;
  z-index: 99;
  top: 10px;
  left: 10px;
}
.map-input {
  position: absolute;
  z-index: 99;
  top: 10px;
  left: 10px;
}
::v-deep {
  .mapboxgl-ctrl-top-right,
  .mapboxgl-ctrl-bottom-right {
    display: none;
  }
}
</style>